<template>
    <div class="Bulletin">      
      <el-text><el-icon size="12"><WarningFilled /></el-icon>{{ state.bulletinFirst.content }}</el-text>      
    </div>
    <div class="affix-container">
      <!-- 固钉展示购物车，购物车里面有表格，展示已选的题目 -->
      <el-affix :offset="60">
        <el-popover
          placement="left-start"
          title="您已选题目："
          :width="950"
          trigger="hover"
        >
          <template #reference>
            <el-badge :value="state.selectQuestionList.length" class="item">
              <el-button :icon="ShoppingCart" size="large" circle/> 
            </el-badge>
          </template>
          <el-table ref="multipleTableRef" class="tableClass" :data="state.selectQuestionList" stripe
            max-height="400"
            :row-style="{height:50+'px'}" 
	          :cell-style="{padding:0+'px'}"
            :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
            :row-key="getRowKeys"
            @selection-change="handleSelectionChange" border
          >
            <el-table-column type="selection" width="35" />
            <el-table-column type="index" width="45" label="序" />
            <el-table-column width="500" property="content" label="内容" show-overflow-tooltip />
            <el-table-column width="100" property="answer" label="答案" show-overflow-tooltip />
            <el-table-column width="200" property="explain" label="解析" show-overflow-tooltip />
            <el-table-column align="right" width="55" >
              <template #header>
                <el-tooltip
                  class="box-item"
                  effect="dark"
                  content="删除选中题"
                  placement="top"
                >
                  <el-icon @click="handeleMultiDelete()"><DeleteFilled /></el-icon>
                </el-tooltip>
              </template>
              <template #default="scope">
                <el-tooltip
                  class="box-item"
                  effect="dark"
                  content="删除该题"
                  placement="top"
                >
                  <el-icon style="width: 1em; height: 1em; margin-right: 1px" @click="handleDelete(scope.$index)">
                    <RemoveFilled />
                  </el-icon>
                </el-tooltip>
                <el-tooltip
                  class="box-item"
                  effect="dark"
                  content="修改该题"
                  placement="top"
                >
                  <Edit style="width: 1em; height: 1em; margin-right: 1px" @click="handleEdit(scope.$index)" />
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
          <div class="tableButton">
            <el-button type="primary" :icon="View" @click="showManyQuestionReadOnlyClick()" >浏览</el-button>
            <el-button type="primary" :icon="Promotion" @click="GroupQuestionListClick()" >组卷</el-button>
          </div>
          
        </el-popover>
      </el-affix>    
    </div>   
   <div class="filter" v-if="currentRouteName==='getQuestionsByPaper'">
      <el-form
        ref="filterInformation"
        :model="state.filterInformation"      
        class="demo-ruleForm"
        :size="formSize"
        status-icon
      >
        <el-form-item label="年级" prop="grade">
          <el-radio-group v-model="state.filterInformation.grade" @change="getQuestionsByFilter">
            <el-radio label="all" >全部</el-radio>
            <el-radio label="七年级" >七年级</el-radio>
            <el-radio label="八年级">八年级</el-radio>
            <el-radio label="九年级">九年级</el-radio>
            <el-radio label="中考">中考</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="阶段" prop="stage">
          <el-radio-group v-model="state.filterInformation.stage" @change="getQuestionsByFilter">
            <el-radio label="all" >全部</el-radio>
            <el-radio label="联考" >联考</el-radio>
            <el-radio label="期中">期中</el-radio>
            <el-radio label="期末">期末</el-radio>
            <el-radio label="模">中考模考</el-radio>
            <el-radio label="真题">中考真题</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年份" prop="year">
          <el-radio-group v-model="state.filterInformation.year"  @change="getQuestionsByFilter">
            <el-radio label="all" >全部</el-radio>
            <el-radio :label="item" v-for="item in getYearList" :key="item" >{{ item }}</el-radio>       
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop="order">
          <el-radio-group v-model="state.filterInformation.order" @change="getQuestionsByFilter">
            <el-radio label="all" >默认</el-radio>
            <el-radio label="-publish_time" >最新</el-radio>
            <el-radio label="publish_time">最旧</el-radio>
          </el-radio-group>
        </el-form-item>    
        <el-form-item label="搜索" prop="key_words">
          <el-input
            v-model="state.filterInformation.key_words"
            style="max-width: 200px"
            placeholder="请输入关键词"
            class="input-with-select"
          >      
            <template #append>
              <el-button :icon="Search" @click="getQuestionsByFilter" />
            </template>
          </el-input>   
        </el-form-item>
      </el-form>
    </div>
    <div class="filter" v-if="currentRouteName==='getQuestionsByKnowledgepoint' || currentRouteName==='getQuestionsByChapter'">
      <el-form
        ref="filterInformation"
        :model="state.filterInformation"      
        class="demo-ruleForm"
        :size="formSize"
        status-icon
      >        
        <el-form-item label="年份" prop="year">
          <el-radio-group v-model="state.filterInformation.year"  @change="getQuestionsByFilterAndChapter">
            <el-radio label="all" >全部</el-radio>
            <el-radio :label="item" v-for="item in getYearList" :key="item" >{{ item }}</el-radio>       
          </el-radio-group>
        </el-form-item>
        <el-form-item label="题型" prop="type">
          <el-radio-group v-model="state.filterInformation.type" @change="getQuestionsByFilterAndChapter">
            <el-radio label="all" >全部</el-radio>
            <el-radio label="1" >选择题</el-radio>
            <el-radio label="2">填空题</el-radio>
            <el-radio label="3">解答题</el-radio>
          </el-radio-group>
        </el-form-item>    
        <!-- <el-form-item label="搜索" prop="key_words">
          <el-input
            v-model="state.filterInformation.key_words"
            style="max-width: 200px"
            placeholder="请输入关键词"
            class="input-with-select"
          >      
            <template #append>
              <el-button :icon="Search" @click="getQuestionsByFilter" />
            </template>
          </el-input>   
        </el-form-item> -->
      </el-form>
    </div>
  <div class="showQuestion">    
    <!-- 用卡片展示题目 -->
    <div  class="questionsBody" id="questionsBodyRef" ></div>
      <div v-for="item in state.questionList" :key="item.id">
        <el-card class="box-card">
            <template #header>
              <div class="card-header">             
                <div class="question-knowledge">
                  <span>知识点：
                    <template v-for="(item_knowledge,index) in item.knowledgepoint" :key="index">
                      {{ item_knowledge.name }};
                    </template>                      
                  </span>
                </div>
                <!-- <div class="others">
                  <span> | 题型：{{item.type_cn}}</span> -->
                <div class="others">
                  <!-- <el-row>
                    <span>难度
                      <el-rate v-model="item.difficulty_level" disabled size="small" :texts="['入门', '容易', '较难', '很难', '压轴']"/>
                    </span>
                  </el-row> -->
                  <span> | 录入时间：{{ item.publish_time.slice(0, 4) }}</span>
                  <!-- <span>日期：{{ item.publish_time }}</span> -->
                  <span> | 来源：{{ item.reference }}</span>
                  <span> | 库币:{{ item.bank_point }}</span>
                  <!-- <div class="operateButton"> -->
                    <template v-if="isFavoriteQuestion(item)==false" >
                      <el-tooltip  class="box-item" effect="light" content="收藏题目" placement="top">
                        <el-button :icon="Star"  size="small" @click="FavoriteQuestion(item)" ></el-button>
                      </el-tooltip>
                    </template>
                    <template v-if="isFavoriteQuestion(item)">
                      <el-tooltip  class="box-item" effect="dark" content="取消收藏" placement="top">
                        <el-button :icon="StarFilled" size="small" @click="cancelFavoriteQuestion(item)" ></el-button>
                      </el-tooltip>
                    </template>
                    
                    <el-tooltip class="box-item" effect="dark" content="查看详情" placement="top">
                      <el-button :icon="View" size="small" @click="viewDetail(item)" ></el-button>
                    </el-tooltip>
                    <el-tooltip class="box-item" effect="light" content="报告错误" placement="top">
                      <el-button :icon="QuestionFilled" size="small" @click="submitFeedback(item)" ></el-button>
                    </el-tooltip>
                    <template v-if="isOwner(item)">
                      <el-tooltip class="box-item" effect="dark" content="更新题目" placement="top">
                        <el-button :icon="EditPen" size="small" @click="updateQuestionClick(item)" ></el-button>
                      </el-tooltip>
                    </template>
                    <el-button type="primary" size="small" @click="addToCart($event, item)" >组</el-button>
                  <!-- </div> -->
                </div>
              </div>
          </template> 
          <div class="card_content">
            <span> 【{{item.type_cn}}】</span>
              <div v-html="item.content" class="line-break"></div>
          </div>
        </el-card>
      </div>
      <!-- 分页展示题目 -->
      <div class="pagination">
        <div v-show="state.isGetQuestionsByKnowledgepoint">
          <el-button type="primary" :icon="Plus" @click="addOneQuestionClick()" >录入单题</el-button>
        </div>
        <!-- <div v-if="state.file !==''">
          <el-button type="warning" :icon="Download" @click="onClickDownloadFile(state.file)" ></el-button>
        </div> -->
        <el-pagination
          background
          layout="total, pre, pager, next"
          :total="total"
          :page-size="size"
          @current-change="handleCurrentChangeFilter"
          v-if="state.getQuestionByFilter == true"
        />
        <el-pagination
          background
          layout="total, pre, pager, next"
          :total="state.total"
          :page-size="state.pageSize"
          @current-change="handleCurrentChange"
          v-else
        />
      </div>

  </div>

  <ViewQuestionDetail ref="viewQuestionDetail" :question="state.question"></ViewQuestionDetail>
  <EditeOneQuestionDialoge ref="editeOneQuestionDialoge" :type="state.type" :fileList="state.fileList" :question="state.question" :father_method="reGetQuestion"></EditeOneQuestionDialoge>
  <AddQuestionDialoge ref="addQuestionDialoge" type="insertWithKnowledgeId" :knowledgepointId="state.knowledgepointId"></AddQuestionDialoge>
  <ShowQuestionReadOnlyDialog ref="showManyQuestionReadOnlyDialog" :questionList="state.selectQuestionList"></ShowQuestionReadOnlyDialog>
  <FeedbackQuestionBug ref="feedbackQuestionBug" :question="state.question" ></FeedbackQuestionBug>
</template>

<script setup>
  import { reactive, ref, onMounted, computed, onUnmounted, watch, getCurrentInstance } from 'vue'
  import axios from '@/utils/axios'
  import { useRoute, useRouter } from 'vue-router'
  import ViewQuestionDetail from '@/views/ViewQuestionDetail.vue'
  import AddQuestionDialoge from '@/views/AddQuestionDialoge.vue'
  import { View, ShoppingCart, Plus, Promotion, QuestionFilled, EditPen, WarningFilled, Star, StarFilled,InfoFilled, Download, Search} from '@element-plus/icons-vue'
  import EditeOneQuestionDialoge from '@/views/EditeOneQuestionDialoge.vue'
  import ShowQuestionReadOnlyDialog from '@/views/ShowQuestionReadOnlyDialog.vue'
  import FeedbackQuestionBug from '@/components/FeedbackQuestionBug.vue'
  import { ElMessage } from 'element-plus'
  import { useStore } from 'vuex'
  import { localGet, localSet, uploadPaperFileServer, deepClone, url_noapi, ExaminationPaperBankPoint } from '@/utils'
  // import { TypeSet } from '@/utils/mathjax'

  // 章节组卷，并且有年份的筛选
  const getQuestionsByFilterAndChapter = ()=>{
    getAllQuestions()
  }
  // 4个选项的筛选试题
  const getQuestionsByFilter = () =>{
    state.getQuestionByFilter = true
    console.log('filter:', state.filterInformation)
    let params = deepClone(state.filterInformation)
    params['page'] = page.value
    params['size'] = size.value
    axios.get('/PaperModelViewSet/filter_four_item/',{params}).then(res => {
      if (res.code==200){
        console.log("筛选得到题目：",res)
        state.questionList = res.data.results
        for(let index=0; index<state.questionList.length;index++ ){
          state.questionList[index].content = modifyDoubleDollarToSingle(state.questionList[index].content)
        }
        console.log('修改后的列表试题：', state.questionList)
        total.value=res.total
        scrollToTop()
      }else{
        ElMessage("获取题目失败")
        console.log("获取题目失败：",res)
        state.total=0
        state.error = res.message
        if (res.code==403){
          ElMessage.error("请重新登录")
          router.push("/login")
        }
      }
    })
    .catch((error)=>{
      console.log("获取目录题目错误：", error)
    })
  }
  const formSize = ref('default')
  // 通过结构，获得appContext变量
  const { appContext } = getCurrentInstance()
  // 获得全局上下文后， 得到$bus事件总线
  const eventBus = appContext.config.globalProperties.$bus
  // （发布）触发本注册的事件:即清空tree组件选中复选框状态  
  const store=useStore()
  const showManyQuestionReadOnlyDialog = ref()
  const editeOneQuestionDialoge = ref()
  const viewQuestionDetail = ref()
  const addQuestionDialoge = ref()
  const feedbackQuestionBug =ref(null)
  const multipleTableRef = ref()
	const select_order_number = ref('') //表格select选中的条数
  const select_orderId = ref([]) //表格select复选框选中的id
  const multipleSelection = ref([])  
  const route = useRoute()
  const router = useRouter()
  let localUser = localGet('user_information')
  // 请求后端api的名称，比如http://x/GetQuestionsByPaper/x或http://x/questions/catalogue/x
  const apiNameMap = {
    getQuestionsByPaper:`/GetQuestionsByPaper/`,
    getQuestionsByGenaralPaper:`/GetQuestionsByPaper/`,
    index:`/questions/`,
    getQuestionsByCourse:`/questions/catalogue/`,
    getQuestionsByChapter:`/questions/catalogue/`,
    getQuestionsBySection:`/questions/catalogue/`,
    getQuestionsByKnowledgepoint:`/questions/catalogue/`
  }

  //为了让前端的代码更易理解，这里做名称映射，后端的api参数比如x/chapter=2或x/paperId=1
  const apiRangeMap = {
    index: 'course',
    getQuestionsByCourse : 'course',
    getQuestionsByChapter : 'chapter',
    getQuestionsBySection : 'section',
    getQuestionsByKnowledgepoint : 'knowledgepoint',
    getQuestionsByPaper:'paper_id',
    getQuestionsByGenaralPaper:'paper_id',
  }
  const page = ref(1)
  const size = ref(10)
  const total = ref(0)
  const state = reactive({
    filterInformation: {
      grade: 'all',
      stage: 'all',
      year: 'all',
      key_words: '',
      order: 'all',
      type: 'all',
    },
    file: '',      //存放按试卷查找的试卷url
    bulletinList: [],   //公告栏通知
    bulletinFirst: {},   // 公告栏第一条通知
    fileList:[],
    id: 0,          // 存储册、章、节、知识点的id，默认的第一册
    page: 1,
    size: 10,
    loading: false, // 列表数据接口返回前的 loading
    questionList: [], // 数据列表
    total: 0, // 总条数
    currentPage: 1, // 当前页
    pageSize: 10, // 分页大小
    knowledgepointId: -1,
    apiName : "/questions/catalogue/",    //后端api名称
    range: "course",      //所有题目的大范围，比如按章、节、课程等
    isGetQuestionsByKnowledgepoint: false,  //是否按照知识点搜索题目，方便判断录入题目
    isgetQuestionsByPaper:false,    //是否联考试题页面，用于新增该联考卷
    paperId:10,                      // 当前页面卷子的id
    selectQuestionList: [],         // 选中的题目，用于组卷
    question: null,
    question_detail: Object,
    type: "modifySelectedQuestion",
    userFavoriteQuestions:[],
    drawer:false,
    token:localGet('token') || "",
    uploadPaperFileServer,
    limit:3,
    questionListUploading:[],       // 将要上传给试卷的题目列表
    showQuestionList:[],            // 用于查看的题目
    secondDrawer:false,              //第2个抽屉的显示
    thirdDrawer:false,              // 第3个抽屉的显示
  })
  // 下载试卷pdf
  const onClickDownloadFile = (file) =>{    
    if (localUser.bank_point < ExaminationPaperBankPoint) {
      ElMessage.warning("库币不足");
      return false;
    } else{
      console.log('即将下载文件：', file)
      
      //发送扣款请求
      let params = {
        paper_id:state.paperId
      } 
      axios.get('/ExaminationPaperViewSet/pay_for_download_file', {params}).then(res => {
        console.log('本次扣款情况：',res)
        if (res.code==200){
          console.log("本次扣款成功")
          localUser.bank_point = res.data.results
        }else if(res.code==201){
          console.log("本次下载无需扣款")
        }else {
          console.log('本次扣款失败')
        }
      })
      .catch((error)=>{
        console.log("扣款请求错误", error)
      })
      //点击链接
      const link = document.createElement('a');
      link.href = file;
      link.setAttribute('download', 'download.pdf');
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link)
    }
  }
  //监听路由变化
  const unWatch = router.beforeEach((to, from, next) => {
    state.apiName = apiNameMap[to.name]
    state.range = apiRangeMap[to.name]   
    const {id, page, size, file} = to.query
    if (id != undefined & id>0){
      state.id = id
    }else{
      state.id=0
    }
    if (page != undefined & page>0){
      state.currentPage = page
    }else{
      state.currentPage = 1
    }
    if (size != undefined & size>0)
    {
      state.size = size
    }else{
      state.size=10
    }
    if (file != undefined & file !== ''){
      state.file = url_noapi + file
    } else{
      state.file = ''
    }
    if (to.name ==="getQuestionsByKnowledgepoint"){
      state.isGetQuestionsByKnowledgepoint = true
      state.knowledgepointId = Number(id)
    }else if (to.name ==="getQuestionsByPaper"){
      state.isgetQuestionsByPaper = true
      state.isGetQuestionsByKnowledgepoint=false
      if(id>0){
        state.paperId = id        
      }
      
    }
    // console.log("路由名：",to.name)
    if(state.apiName != undefined){
      getAllQuestions()
    }    
    next(true)
  })
const TypeSet = async function (elements) {
  if (!window.MathJax) {
      return
  }
  window.MathJax.startup.promise = window.MathJax.startup.promise
      .then(() => {
          return window.MathJax.typesetPromise(elements)
      })
      .catch((err) => console.log('Typeset failed: ' + err.message))
  return window.MathJax.startup.promise
}
onMounted(()=>{
    state.questionList=state.questionList.splice(0)
    state.range = apiRangeMap[route.name]
    state.apiName = apiNameMap[route.name]
    const {id} = route.query
    if (id != undefined & id>0){state.id = id}
    state.currentPage = 1
    // console.log("路由名：",route.name)
    getAllQuestions()
    // getAllFavoriteQuestions()
    getBulletin()
    TypeSet()
  })
  watch(()=> state.questionList,
  (newValue)=>{
    //直接调用TypeSet()也可以，但是会重新渲染页面所有公式
    TypeSet()
  })
  onUnmounted(()=>{
    unWatch()
  })
  // 获取通告栏内容
  const getBulletin = () => {
    const getBulletinCache = localGet('getBulletinCache')
    const getBulletinCacheStartTime = localGet('getBulletinCacheStartTime')
    console.log('getBulletinCache:', getBulletinCache)
    console.log('getBulletinCacheStartTime:', getBulletinCacheStartTime)
    const currentDate = new Date();
    const currentYear = currentDate.getFullYear()
    const currentMonth = currentDate.getMonth() + 1
    const currentDay = currentDate.getDate()
    const currentTime = currentYear*10000 + currentMonth * 100 + currentDay
    if(getBulletinCache!=undefined && getBulletinCacheStartTime!=undefined && getBulletinCacheStartTime>20240000){   
        const dateDiff = currentTime - getBulletinCacheStartTime
        if(dateDiff <=1){
          if(getBulletinCache!=[]){
            console.log('从缓存恢复公告栏')
            state.bulletinList = getBulletinCache
            state.bulletinFirst = state.bulletinList[state.bulletinList.length -1]
            return 1
          }
        } 
    }
    axios.get('/BulletinModelViewSet/get_bulletin').then(res => {
      if (res.code==200){
        // console.log("后台获取公告栏",res)
        state.bulletinList = res.data.results
        state.bulletinFirst = state.bulletinList[state.bulletinList.length -1]
        localSet('getBulletinCache', res.data.results)
        localSet('getBulletinCacheStartTime', currentTime)
      }else{
        console.log("获取公告栏失败：",res)
      }
    })
    .catch((error)=>{
      console.log("获取公告栏错误：", error)
    })   
  }
  // 把双$符号改成单$符号
  const modifyDoubleDollarToSingle=(content_str) =>{
    while(content_str.includes('$$')){
      content_str = content_str.replace('$$', '$');
    }
    while(content_str.includes('\\\\')){
      content_str = content_str.replace('\\\\', '\\');
    }
    return content_str
  }
  // 重新获取题目
  const reGetQuestion=()=>{
    getAllQuestions()
    getAllFavoriteQuestions()
  }
  // 获取章节目录搜索到所有题目
  const getAllQuestions=()=>{
    let params={
        page: state.currentPage,
        size: state.pageSize,
        year: state.filterInformation.year,
        type: state.filterInformation.type,
      }
      if(state.id>0){
        params[state.range]=state.id
      }
      // console.log("请求参数：",params)
      // console.log("请求api",state.apiName)
    axios.get(state.apiName,{params}).then(res => {
      if (res.code==200){
        console.log("列表题目：",res)
        state.questionList = res.data.results
        for(let index=0; index<state.questionList.length;index++ ){
          state.questionList[index].content = modifyDoubleDollarToSingle(state.questionList[index].content)
        }
        console.log('修改后的列表试题：', state.questionList)
        state.total=res.total
        scrollToTop()
      }else{
        ElMessage("获取题目失败")
        console.log("获取题目失败：",res)
        state.total=0
        state.error = res.message
        if (res.code==403){
          ElMessage.error("请重新登录")
          router.push("/login")
        }
      }
    })
    .catch((error)=>{
      console.log("获取目录题目错误：", error)
    })   
  }
  //添加单题按钮，显示弹窗录入题目
  const addOneQuestionClick=()=>{
    const {id}=route.query
    state.knowledgepointId=Number(id)
    addQuestionDialoge.value.open(state.knowledgepointId)
  }
   //点击页码时触发
  const handleCurrentChangeFilter = (newPage)=>{
    page.value = newPage 
    getQuestionsByFilter()
    document.querySelector('#questionsBodyRef').scrollIntoView(true);
  }
  //点击页码时触发
  const handleCurrentChange = (newPage)=>{
    state.currentPage = newPage 
    getAllQuestions()
    document.querySelector('#questionsBodyRef').scrollIntoView(true);
  }
  //更改每页数量时触发
  const handleSizeChange = (newSize)=>{
    state.pageSize = newSize
    state.currentPage=1
    getAllQuestions()
    document.querySelector('#questionsBodyRef').scrollIntoView(true);
  }
  const scrollToTop=()=>{
    document.querySelector('#questionsBodyRef').scrollIntoView(true);
  }

  //查看单个题目详情
  const viewDetail = (item)=>{
    state.question = item
    viewQuestionDetail.value.open(item)
  }
  //提交题目bug反馈
  const submitFeedback = (item)=>{
    if(item){
      feedbackQuestionBug.value.open(item)
    }
  }
  //添加到购物车
  const addToCart = (event, item)=>{
    event.target.innerText = "已选"
    state.selectQuestionList.push(item)

  }
  //删除当前行所在的
  const handleDelete = (index) => {
    state.selectQuestionList.splice(index,1)
  }
  //编辑当前行的数据，将选中的内容赋值给state.question，待传给子组件, 并且深拷贝
  const handleEdit = (index)=> {
    state.type = "modifySelectedQuestion"
    state.question = JSON.parse(JSON.stringify(state.selectQuestionList[index]))
    editeOneQuestionDialoge.value.open(index, state.question)
  }
  //删除选中的行
  const handeleMultiDelete = ()=>{ 
    for (const i in select_orderId.value){
      state.selectQuestionList.splice(i, 1)
    }
  }
  //选中的list
  const getRowKeys = (row) => {
      //记录每行的key值
      return row.id;
    }
//当表格选择项发生变化时会触发该事件
  const handleSelectionChange = (val) => {
      // 解决来回切换页面，也无法清除上次选中情况
      console.log('选中发生变化了：', val)
      multipleSelection.value = val;
      select_order_number.value = multipleSelection.value.length;
      select_orderId.value = [];   //清空，再遍历加入
      if (val) {
        val.forEach((row) => {
          if (row) {  
            select_orderId.value.push(row.id);
          }
        });
      }
      
  }
  // 查看购物车已选题目列表
  const showManyQuestionReadOnlyClick = ()=>{
    // 打开弹窗
    if(state.selectQuestionList.length>0){
      state.showQuestionList=deepClone(state.selectQuestionList)
      showManyQuestionReadOnlyDialog.value.open(state.showQuestionList)
    }else{
      ElMessage.warning( '请勾选题目！')
    }    
  }

  // 选中的题目存入全局状态，addPaperBySelectQuestionList把选中的题目列表提交给后台，生成docx文件，后台返回该docx的url
  const GroupQuestionListClick = ()=>{
    if(state.selectQuestionList.length==0){
      ElMessage.error("还没加入题目！")
      return false
    }
    store.commit('setSelectQuestionList', state.selectQuestionList)
    store.commit('setIsPrivate', false)
    router.push("/addPaperBySelectQuestionList")
  }
  const isOwner = (question) =>{    
    let localUser = localGet('user_information')
    return localUser.username == question.owner_info.username
  }
  // 更新题目按钮处理
  const updateQuestionClick=(questionItem)=>{
    console.log("更新题目之前内容：",questionItem)
    state.type = "update"
    state.question = deepClone(questionItem)
    editeOneQuestionDialoge.value.open(0, state.question)
  }
  // 当前页面是某个具体试卷，且登录的用户是管理员
  const isStaffAndPaper=()=>{
    let localUser = localGet('user_information')
    let selectedPaper = store.state.paper
    return localUser.is_staff == true && route.name == 'getQuestionsByPaper'
  }
  // 获取当前路由名
  const currentRouteName = computed(()=>route.path.split('/').pop())
  function fillArray(a, b) {
    let result = [];
    for (let i = a; i <= b; i++) {
        result.push(i);
    }
    return result;
}
  // 获取当前年份，并组成年份数组，从2024年开始,并转换为字符串
  const getYearList = computed(()=>fillArray(2024,new Date().getFullYear()).map(String))
  // 收藏该题目
  const FavoriteQuestion=(item)=>{
    let params={ question_id: item.id}
    axios.post(`/UserFavoriteQuestionAPIView/`, params).then(res => {
      if (res.code==200){
        ElMessage.success("收藏题目成功！")
        state.userFavoriteQuestions = res.data.results
      }else{
        ElMessage("收藏题目失败")
        if (res.code==403){
          ElMessage.error("请重新登录")
          router.push("/login")
        }
      }
    })
    .catch((error)=>{
      console.log("收藏题目错误", error)
    })   
  }

  // 该题目是否被收藏
  const isFavoriteQuestion=(item)=>{
    let flag = false
    for(let question of state.userFavoriteQuestions){
      if (question.id == item.id){
        flag = true
        break
      }
    }
    return flag
  }
  // 获取该用户所有收藏的题目, 不分页的所有题目
  const getAllFavoriteQuestions=()=>{
    axios.get(`/GetAllFavoriteQuestionsAPIView/`).then(res => {
      if (res.code==200){
        state.userFavoriteQuestions = res.data.results       
      }else{
        ElMessage.error("获取收藏题目失败")
        if (res.code==403){
          ElMessage.error("请重新登录")
          // router.push("/login")
        }
      }
    })
    .catch((error)=>{
      console.log("获取收藏题目错误", error)
    })   
  }
// 取消收藏该题目
const cancelFavoriteQuestion=(item)=>{
    let params={ question_id: item.id}
    axios.delete(`/UserFavoriteQuestionAPIView?question_id=`+item.id).then(res => {
    // axios.delete(`/UserFavoriteQuestionAPIView/`,{params}).then(res => {
    // axios.delete('/UserFavoriteQuestionAPIView/', params).then(res => {
      if (res.code==200){
        ElMessage.success("取消收藏成功！")
        state.userFavoriteQuestions = res.data.results
      }else{
        ElMessage.error("取消收藏失败")
        if (res.code==403){
          ElMessage.warning("请重新登录")
          // router.push("/login")
        }
      }
    })
    .catch((error)=>{
      console.log("取消收藏错误", error)
    })   
  }

</script>
<style scoped>
html, body {
	width: 100%;
	height: 100%;
}
.showQuestion{
  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
  justify-content: center;
  align-items: flex-end;
  font-size: 12px;
  margin: 1;
  padding: 1;
}
  .card-header {
    display: flex;
    justify-content:flex-end;
    align-items: flex-start;
    flex-flow: row nowrap;
    font-size: 12px;
    margin: 0;
    padding: 0;
    height: 20px;
  }
  .question-knowledge{
    display: flex;
    flex-flow: row wrap;
    justify-content: space-between;
    align-items: flex-start;
    /* margin: 2rpx; */
  }
  .others{
    /* margin: 2rpx; */
    display: flex;
    flex-flow: row nowrap;
    justify-content: flex-end;
    align-items: center;
  }
  .card_content {
    display: flex;
    flex-flow: column wrap;
    margin: 0px;
    padding: 0px;
  }
  .text {
    font-size: 12px;
  }
  .item {
    margin-bottom: 1px;
  }
  .box-card {
    display: flex;
    flex-flow: column wrap;
    align-items: stretch;
    height: auto;
    width: 100%;
    overflow-y: auto;
  }
  .line-break{
  white-space: pre-wrap;
  width: 950px;
  font-size: 16px;
  }
  img{
      display:block;
  }
  .affix-container{
    text-align: right;
    margin: 0 20px 0 0;
  }
  
.tableClass .cell{   
    padding: 0!important;
    height: 20px!important;
    line-height: 20px!important;
    text-align: center;
    font-size: 10px;
  }
  .tableButton{
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
  }
  .questionsBody{
    display: flex;
    flex-direction: column;
    flex-wrap: wrap;
    align-items: stretch;
    overflow-y: auto;
    margin: 0;
    padding: 0;
  }
  .addOneQuestionButton{
    margin: 0;
    padding: 0;
  }
  .pagination{
    display: flex;
    flex-flow: row nowrap;
    justify-content: center;
    align-items: center;
  }
  /* .operateButton{
    padding: 0;
    margin: 0;
    display: flex;
    flex-flow: row nowrap;
  } */
  .linkKnowledgepoint{
    display: flex;
    flex-flow: row nowrap;
  }
  .Bulletin {
    width: 450px;
    margin: 0;
    padding: 0;
    height: 22px;
    font-size: xx-small;
    white-space: nowrap;
    animation: scroll 10s linear infinite;
  }
  @keyframes scroll {
  0% { transform: translateX(100%); }
  100% { transform: translateX(-100%); }
}
/*
user-select: auto|none|text|all;
auto	默认。如果浏览器允许，则可以选择文本。
none	防止文本选取。
text	文本可被用户选取。
all	    单击选取文本，而不是双击。
*/
*{
user-select:none;
}

.prohibitSel{
user-select:none;
}
.filter {
  margin: 5px;
  padding: 3px;
}
</style>